package com.fzt.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.admin.common.biz.user.UserContext;
import com.fzt.admin.common.convention.exception.ClientException;
import com.fzt.admin.common.convention.exception.ServiceException;
import com.fzt.admin.common.convention.result.Result;
import com.fzt.admin.dao.entity.GroupDO;
import com.fzt.admin.dao.mapper.GroupMapper;
import com.fzt.admin.dto.req.ShortLinkGroupSaveReqDTO;
import com.fzt.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.fzt.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.fzt.admin.dto.resp.ShortLinkGroupRespDTO;
import com.fzt.admin.remote.dto.ShortLinkRemoteService;
import com.fzt.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.fzt.admin.service.GroupService;
import com.fzt.admin.util.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.fzt.admin.common.constant.RedisCacheConstant.LOCK_GROUP_VREATE_KEY;

/*
短链接接口实现层
 */
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num")
    private Integer groupMaxNum;

    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService(){};

    @Override
    public void saveGroup(ShortLinkGroupSaveReqDTO reqParam) {
        GroupDO group;
        String gid;
        RLock lock = redissonClient.getLock(LOCK_GROUP_VREATE_KEY + UserContext.getUsername());
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> qw = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(qw);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum){
                throw new ClientException("分组超出最大分组数:" + 20);
            }
            do {
                gid = RandomGenerator.generateRandomString();
                LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                        .eq(GroupDO::getGid, gid);
                group = baseMapper.selectOne(queryWrapper);
            }while (group != null);

            GroupDO groupDO = GroupDO.builder()
                    .gid(gid)
                    .username(UserContext.getUsername())
                    .name(reqParam.getName())
                    .sortOrder(0)
                    .build();
            int count = baseMapper.insert(groupDO);
            if (count < 1){
                throw new ServiceException("短链接新增失败");
            }
        }finally {
            lock.unlock();
        }

    }

    @Override
    public void saveGroup(String username, ShortLinkGroupSaveReqDTO reqParam) {
        GroupDO group;
        String gid;
        do {
            gid = RandomGenerator.generateRandomString();
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getGid, gid);
            group = baseMapper.selectOne(queryWrapper);
        }while (group != null);

        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .username(username)
                .name(reqParam.getName())
                .sortOrder(0)
                .build();
        int count = baseMapper.insert(groupDO);
        if (count < 1){
            throw new ServiceException("短链接新增失败");
        }
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO reqDTO) {
        LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getGid, reqDTO.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername());
        int count = baseMapper.update(BeanUtil.copyProperties(reqDTO, GroupDO.class), eq);
        if (count < 1){
            throw new ServiceException("分组修改失败");
        }
    }

    @Override
    public void deleteGroup(String gid) {//逻辑删除
        LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, UserContext.getUsername());
        GroupDO groupDO = GroupDO.builder()
                .delFlag(1)
                .build();
        int count = baseMapper.update(groupDO, eq);
        if (count < 1){
            throw new ServiceException("删除失败");
        }
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> reqDTO) {
        reqDTO.forEach(shortLinkGroupSortReqDTO ->{
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(shortLinkGroupSortReqDTO.getSortOrder())
                    .gid(shortLinkGroupSortReqDTO.getGid())
                    .username(UserContext.getUsername())
                    .build();

            LambdaUpdateWrapper<GroupDO> eq = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, groupDO.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO,eq);
        });
    }

}
